﻿using System;
using System.Web;
using System.Web.Caching;

namespace Repo.DataCaching
{
    public class LastUpdatedCache
    {
        private const string LastUpdated = "LastUpdated";

        private static string GetLastUpdatedKey(string cacheKey)
        {
            if (cacheKey.IndexOf(LastUpdated) == -1)
            {
                return LastUpdated + ";" + cacheKey;
            }
            return cacheKey;
        }

        public static bool CacheNeedsReseting(DateTime dtResetCheck, string cacheKey)
        {
            var lastUpdated = GetLastUpdated(cacheKey);
            if (lastUpdated != null)
            {
                return dtResetCheck > lastUpdated;
            }
            return true;
        }

        public static DateTime? GetLastUpdated(string cacheKey)
        {
            var lastUpdatedkey = GetLastUpdatedKey(cacheKey);
            var lastUpdated = HttpRuntime.Cache[lastUpdatedkey];
            if (lastUpdated != null)
            {
                return (DateTime) lastUpdated;
            }
            return null;
        }

        public static void SaveLastUpdated(string cacheKey)
        {
            var expiry = new TimeSpan(365, 0, 0, 0);
            var lastUpdatedkey = GetLastUpdatedKey(cacheKey);
            DeleteLastUpdated(lastUpdatedkey);
            HttpRuntime.Cache.Add(lastUpdatedkey, DateTime.Now, null, DateTime.Now.Add(expiry),
                                  Cache.NoSlidingExpiration, CacheItemPriority.High, null);
        }

        public static bool DeleteLastUpdated(string cacheKey)
        {
            var lastUpdatedkey = GetLastUpdatedKey(cacheKey);
            if (HttpRuntime.Cache.Get(lastUpdatedkey) != null)
            {
                HttpRuntime.Cache.Remove(lastUpdatedkey);
                return true;
            }
            return false;
        }
    }
}
